﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace TSites.Utility.Captcha
{
	public class SimpleCaptcha : AbstractCaptcha, IDisposable
	{
		public SimpleCaptcha(int width, int height)
			: base(width, height)
		{ }

		/// <summary>
		/// Generate the captcha output image
		/// </summary>
		/// <returns></returns>
		public override Bitmap GenerateCaptcha(string captcha)
		{
			Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);

			Graphics g = Graphics.FromImage(bmp);
			g.SmoothingMode = SmoothingMode.AntiAlias;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			HatchBrush brush = new HatchBrush(HatchStyle.Weave, Color.LightGray, Color.White);
			g.FillRectangle(brush, rect);

			//g.FillPath(brush, path);
			g.DrawString(captcha, CaptchaFont, Brushes.Black, new PointF(10, 0));

			AddNoise(g);

			// Clean up.
			brush.Dispose();
			g.Dispose();

			return bmp;
		}

		private void AddNoise(Graphics g)
		{
			System.Random rand = new System.Random();
			int posX, posY, width, height;
			for (int i = 1; i < 50; i++)
			{
				posX = rand.Next(1, Width);
				posY = rand.Next(1, Height);
				width = rand.Next(3);
				height = rand.Next(3);
				g.DrawEllipse(Pens.Black, posX, posY, width, height);
			}
		}

		#region IDisposable Members

		public void Dispose()
		{
			CaptchaFont.Dispose();
			GC.SuppressFinalize(this);
			this.Dispose();
		}

		#endregion
	}
}
